import { login, logout, getInfo } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';
import defAva from '@/assets/images/profile.jpg';
import { deepClone } from '../../utils';
import { UserInfo } from '#/store';

const deepUser: UserInfo = {
  userInfo: {},
  token: getToken(),
  id: '',
  name: '',
  avatar: '',
  roles: [],
  permissions: [],
};
const useUserStore = defineStore('user', {
  state: (): UserInfo => deepClone(deepUser) as UserInfo,
  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['token', 'userInfo', 'roles', 'permissions', 'id', 'name', 'avatar'],
  },
  getters: {
    phonenumber(state) {
      const str = state.userInfo.phonenumber;
      return str?.replace(/^(\d{3})\d{4}(\d{4})/, '$1****$2');
    },
  },
  actions: {
    // 登录
    login(userInfo) {
      userInfo.username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((res: any) => {
            if (res.code === 200 || res.token) {
              this.setToken(res.token);
            }
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res: any) => {
            const user = res.user;
            this.userInfo = user;
            const avatar =
              user.avatar == '' || user.avatar == null
                ? defAva
                : import.meta.env.VITE_APP_BASE_API + user.avatar;

            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.roles = res.roles;
              this.permissions = res.permissions;
            } else {
              this.roles = ['ROLE_DEFAULT'];
            }
            this.id = user.userId;
            this.name = user.nickName;
            this.avatar = avatar;
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    setToken(token) {
      setToken(token);
      this.token = token;
    },

    resetState() {
      const stateDeepUser = deepClone(deepUser);
      Object.keys(stateDeepUser).map((key) => {
        this[key] = stateDeepUser[key];
      });
      this.token = '';
      removeToken();
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        if (this.token) {
          logout()
            .then(() => {
              this.resetState();
              resolve(null);
            })
            .catch((error) => {
              this.resetState();
              reject(error);
            });
        } else {
          resolve(null);
        }
      });
    },
  },
});

export default useUserStore;
